package top.lyf1210.yuwenpicturebackend.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.web.multipart.MultipartFile;
import top.lyf1210.yuwenpicturebackend.config.CosClientConfig;
import top.lyf1210.yuwenpicturebackend.constant.UserAuthConstant;
import top.lyf1210.yuwenpicturebackend.enums.PictureReviewStatusEnum;
import top.lyf1210.yuwenpicturebackend.enums.UserRole;
import top.lyf1210.yuwenpicturebackend.exception.BusinessException;
import top.lyf1210.yuwenpicturebackend.exception.ErrorCode;
import top.lyf1210.yuwenpicturebackend.exception.ThrowUtils;
import top.lyf1210.yuwenpicturebackend.manager.CosManager;
import top.lyf1210.yuwenpicturebackend.manager.FileManager;
import top.lyf1210.yuwenpicturebackend.manager.upload.FilePictureUpload;
import top.lyf1210.yuwenpicturebackend.manager.upload.PictureUploadTemplate;
import top.lyf1210.yuwenpicturebackend.manager.upload.UrlPictureUpload;
import top.lyf1210.yuwenpicturebackend.model.Picture;
import top.lyf1210.yuwenpicturebackend.model.Space;
import top.lyf1210.yuwenpicturebackend.model.User;
import top.lyf1210.yuwenpicturebackend.model.dto.picture.*;
import top.lyf1210.yuwenpicturebackend.model.dto.file.UploadPictureDetail;
import top.lyf1210.yuwenpicturebackend.model.vo.picture.PictureVO;
import top.lyf1210.yuwenpicturebackend.model.vo.user.UserVO;
import top.lyf1210.yuwenpicturebackend.service.PictureService;
import top.lyf1210.yuwenpicturebackend.mapper.PictureMapper;
import org.springframework.stereotype.Service;
import top.lyf1210.yuwenpicturebackend.service.SpaceService;
import top.lyf1210.yuwenpicturebackend.service.UserService;
import top.lyf1210.yuwenpicturebackend.utils.ColorSimilarUtils;
import top.lyf1210.yuwenpicturebackend.utils.FlushPictureColors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

import static top.lyf1210.yuwenpicturebackend.constant.FileConstant.*;
import static top.lyf1210.yuwenpicturebackend.constant.OrderConstant.ASC;

/**
* @author 钰玟
* @description 针对表【t_picture(图片)】的数据库操作Service实现
* @createDate 2025-04-17 14:10:32
*/
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{

    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Resource
    private  UserService userService;
    @Resource
    private CosManager cosManager;
    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    @Lazy
    private SpaceService spaceService;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private FlushPictureColors flushPictureColors;
    @Resource
    private PictureMapper pictureMapper;

    /**
     * 上传图片
     * @param inputSource 图片文件
     * @param pictureUploadDTO dto
     * @param loginUser 操作用户
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadDTO pictureUploadDTO, User loginUser) {
        if(inputSource == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,PICTURE_FAIL_UPLOAD);
        }


        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
// 校验空间是否存在
        Long spaceId = pictureUploadDTO.getSpaceId();
        if (spaceId != null) {
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            // 必须空间创建人（管理员）才能上传
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }

        }

        //先判断操作类型
        Long pictureId = null;
        if(pictureUploadDTO !=null){
            pictureId = pictureUploadDTO.getId();
        }
        //如果是更新图片，则应可以在数据库中查询到该图片
        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或管理员可编辑
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 校验空间是否一致
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        //判断 上传图片方式类型
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if(inputSource instanceof String){
            pictureUploadTemplate = urlPictureUpload;
        }
        //上传图片
        //用户Id作为每个用户的图库前缀
        String uploadPrefix;
        // 按照用户 id 划分目录 => 按照空间划分目录
        if (spaceId == null) {
            uploadPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPrefix = String.format("space/%s", spaceId);
        }

        UploadPictureDetail uploadPictureDetail = pictureUploadTemplate.uploadPicture(inputSource, uploadPrefix);
        //构造要入库的图片基本信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureDetail.getUrl());
        String picName = uploadPictureDetail.getPicName();
        if(pictureUploadDTO !=null && StrUtil.isNotBlank(pictureUploadDTO.getPicName())){
            picName = pictureUploadDTO.getPicName();
        }
        //设置颜色属性
        picture.setPicColor(uploadPictureDetail.getPicColor());
        picture.setName(picName);
        picture.setPicSize(uploadPictureDetail.getPicSize());
        picture.setPicWidth(uploadPictureDetail.getPicWidth());
        picture.setPicHeight(uploadPictureDetail.getPicHeight());
        picture.setPicScale(uploadPictureDetail.getPicScale());
        picture.setPicFormat(uploadPictureDetail.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setThumbnailUrl(uploadPictureDetail.getThumbnailUrl());
        picture.setSpaceId(spaceId);
        //如果pictureId 不为空 => 更新，否则是新增

        //审核参数
        this.fillReviewParams(picture, loginUser);
        if(pictureId != null){
            //如果是更新，则补充 id和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        //插入/更新
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });

        return PictureVO.objToVo(picture);
    }

    /**
     * 分页查询图片列表
     * @param pictureQueryDTO
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryDTO pictureQueryDTO) {
        //创建条件构造器
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryDTO == null) {
            //判断条件是否为空
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryDTO.getId();
        String name = pictureQueryDTO.getName();
        String introduction = pictureQueryDTO.getIntroduction();
        String category = pictureQueryDTO.getCategory();
        List<String> tags = pictureQueryDTO.getTags();
        Long picSize = pictureQueryDTO.getPicSize();
        Integer picWidth = pictureQueryDTO.getPicWidth();
        Integer picHeight = pictureQueryDTO.getPicHeight();
        Double picScale = pictureQueryDTO.getPicScale();
        String picFormat = pictureQueryDTO.getPicFormat();
        String searchText = pictureQueryDTO.getSearchText();
        Long userId = pictureQueryDTO.getUserId();
        Integer reviewStatus = pictureQueryDTO.getReviewStatus();
        Long reviewerId = pictureQueryDTO.getReviewerId();
        String reviewMessage = pictureQueryDTO.getReviewMessage();
        Long spaceId = pictureQueryDTO.getSpaceId();
        boolean nullSpaceId = pictureQueryDTO.isNullSpaceId();
        Date startEditTime = pictureQueryDTO.getStartEditTime();
        Date endEditTime = pictureQueryDTO.getEndEditTime();


        //继承自 pageDTO
        String sortField = pictureQueryDTO.getSortField();
        String sortOrder = pictureQueryDTO.getSortOrder();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件  == 模糊查询
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        //其他字段的 精准查询
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals(ASC), sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = pictureVO.getUserId();
        if(userId!=null&&userId>0){
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 获取vo列表
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if(CollUtil.isEmpty(pictureList)){
            return pictureVOPage;
        }
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        //1.关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long,List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        //2.填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if(userIdUserListMap.containsKey(userId)){
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }

    /**
     * 判断图片是否合法
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, ID_CAN_NOT_BE_NULL);
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, URL_TOO_LONG);
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, PROFILE_TOO_LONG);
        }
    }

    /**
     * 审核图片
     * @param pictureReviewDTO 审核图片
     * @param loginUser
     */
    @Override
    public void doPictureReview(PictureReviewDTO pictureReviewDTO, User loginUser) {
        //判断 dto中的图片id
        Long id = pictureReviewDTO.getId();
        Integer reviewStatus = pictureReviewDTO.getReviewStatus();
        PictureReviewStatusEnum enumByValue = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if(id==null || reviewStatus==null ||PictureReviewStatusEnum.REVIEWING.equals(enumByValue)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //判断数据库中是否有该图片
        Picture picture = this.getById(id);
        ThrowUtils.throwIf(picture==null,ErrorCode.PARAMS_ERROR);
        if(picture.getReviewStatus().equals(reviewStatus)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"请勿重复审核");
        }
        //提交审核
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewDTO,updatePicture);
        //补充的字段  1. 修改者id
        updatePicture.setReviewerId(loginUser.getId());
        //2. 修改时间
        updatePicture.setReviewTime(new Date());
        boolean result = updateById(updatePicture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
    }

    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        //1.管理员，直接通过审核
        if(userService.isAdmin(loginUser)){
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员审核通过");
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
        }
        //2.用户，自动填充为 Reviewing
        picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
    }

    /**
     * 批量上传图片
     * @param pictureUploadByBatchDTO 上传图片
     * @param loginUser 当前用户
     * @return 图片数量
     */
    @Override
    public Integer pictureUploadByBatch(PictureUploadByBatchDTO pictureUploadByBatchDTO, User loginUser) {

        //1. 获取查找图片的关键词
        String searchText = pictureUploadByBatchDTO.getSearchText();
        Integer count = pictureUploadByBatchDTO.getCount();
        ThrowUtils.throwIf(count>30,ErrorCode.PARAMS_ERROR,"最多30条");
        String namePrefix = pictureUploadByBatchDTO.getNamePrefix();
        if(StrUtil.isBlank(namePrefix)){
            namePrefix = searchText;
        }                                //https://cn.bing.com/images/async?q=%s&mmasync=1
        //2. 要抓取的地址                  https://cn.bing.com/images/async?q=%25s&mmasync=1
/*        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1",searchText);
        Document document;
        try {
            document  = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if(ObjUtil.isNull(div)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取元素失败");
        }
        Elements imageElementList = div.select("img.ming");
        int uploadCount = 0 ;
        for (Element imageElement : imageElementList) {
            String fileUrl = imageElement.attr("src");
            if(StrUtil.isBlank(fileUrl)){
                log.debug("当前链接为空,已跳过:"+ fileUrl);
                continue;
            }
            //处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if(questionMarkIndex>-1){
                fileUrl = fileUrl.substring(0,questionMarkIndex);
            }
            //3.上传图片
            PictureUploadDTO pictureUploadDTO = new PictureUploadDTO();
            if(StrUtil.isNotBlank(namePrefix)){
                pictureUploadDTO.setPicName(namePrefix+(uploadCount+1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl,pictureUploadDTO,loginUser);
                log.debug("上传图片成功,id = "+pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("上传图片失败",e);
//                throw new RuntimeException(e);
                continue;
            }
            if(uploadCount>= count){
                break;
            }
        }
        return uploadCount;*/
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
//        Elements imgElementList = div.select("img.mimg");
        //TODO start
        Elements imgElementList = div.select(".iusc");//TODO  1.获取高清图像
        int uploadCount = 0;
        for (Element imgElement : imgElementList) {
//            String fileUrl = imgElement.attr("src");


            String dataM = imgElement.attr("m");//TODO  2.获取data-m中属性的json字符串
            String fileUrl;
            //TODO  3.解析Json字符串
            try {
                JSONObject jsonObject = JSONUtil.parseObj(dataM);
                fileUrl = jsonObject.getStr("murl");
            }catch (Exception e){
                log.error("解析图片数据失败",e);
                continue;
            }
            //TODO end
            if (StrUtil.isBlank(fileUrl)) {
                log.debug("当前链接为空，已跳过:"+ fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }
            // 上传图片
            PictureUploadDTO pictureUploadDTO = new PictureUploadDTO();
            if(StrUtil.isNotBlank(namePrefix)){
                pictureUploadDTO.setPicName(namePrefix+(uploadCount+1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadDTO, loginUser);
                log.debug("图片上传成功, id = "+pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败", e);
                continue;
            }
            if (uploadCount >= count) {
                break;
            }
        }
        return uploadCount;
    }

    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        // 判断该图片是否被多条记录使用
        String pictureUrl = oldPicture.getUrl();
        long count = this.lambdaQuery()
                .eq(Picture::getUrl, pictureUrl)
                .count();
        // 有不止一条记录用到了该图片，不清理
        if (count > 1) {
            return;
        }
        //提取路径部分
        try {
            String picturePath = new URL(pictureUrl).getPath();
            cosManager.deleteObject(picturePath);
            String thumbnailUrl = oldPicture.getThumbnailUrl();
            if(StrUtil.isNotBlank(picturePath)){
                String thumbnailPath =new URL(thumbnailUrl).getPath();
                cosManager.deleteObject(thumbnailPath);
            }
        } catch (MalformedURLException e) {
            log.error("图片地址错误,url{}"+pictureUrl, e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片地址错误");
        }
    }

    /**
     * 检验图片操作者对应的权限
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        //判断是否是公共图库
        if(picture.getSpaceId()==null){
            //只有本人和管理员可以操作
            if(!loginUser.getId().equals(picture.getUserId())&&!UserAuthConstant.ADMIN_ROLE.equals(loginUser.getUserRole())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        else{
            //私有空间，只有本人可以操作
            if(!loginUser.getId().equals(picture.getUserId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    /**
     * 删除图片
     * @param pictureId 待删除的图片
     * @param loginUser 操作的用户
     * @return
     */
    @Override
    public Boolean deletePicture(Long pictureId, User loginUser) {
        //判断删除id的是否合法
        ThrowUtils.throwIf(pictureId<0, ErrorCode.PARAMS_ERROR);
        //获取id对应的图片
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture==null,ErrorCode.NOT_FOUND_ERROR);
        //判断是否有删除的权限 本用户的图片，或者为管理员才可以删除
        if(!loginUser.getId().equals(picture.getUserId())&&!UserAuthConstant.ADMIN_ROLE.equals(loginUser.getUserRole())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //鉴权，改为注解鉴权
//        this.checkPictureAuth(loginUser,picture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
            // 释放额度
            Long spaceId = picture.getSpaceId();
            if (spaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + picture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(picture);
        return true;
    }

    /**
     * 编辑图片信息
     * @param pictureEditDTO 编辑图片的信息
     * @param loginUser 操作的用户
     * @return
     */
    @Override
    public Boolean editPicture(PictureEditDTO pictureEditDTO, User loginUser) {
        //判断编辑的图片dto
        ThrowUtils.throwIf(pictureEditDTO==null,ErrorCode.PARAMS_ERROR);
        //将dto转化为 entity
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureEditDTO,picture);
        //转化tags
        picture.setTags(JSONUtil.toJsonStr(pictureEditDTO.getTags()));
        //设置修改时间
        picture.setEditTime(new Date());
        //数据校验
        this.validPicture(picture);
        //获取该图片，判断是否存在
        long id = pictureEditDTO.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf( oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
        //鉴权，改为注解鉴权
//        this.checkPictureAuth(loginUser,oldPicture);

        //审核参数
        this.fillReviewParams(picture,loginUser);
        //插入数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);
        return result;
    }

    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        //1.校验参数 颜色参数、用户参数
        ThrowUtils.throwIf(spaceId == null||StrUtil.isBlank(picColor),ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null , ErrorCode.NO_AUTH_ERROR);
        //2. 校验空间权限 === 颜色查询只在空间下才有效
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        //无该空间 的 权限
        if(!loginUser.getId().equals(space.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }
        //3. 查询该空间下的图片的颜色信息
        List<Picture> pictureList = this.lambdaQuery()
                //属于该空间
                .eq(Picture::getSpaceId, spaceId)
                //颜色信息不能为空
                .isNotNull(Picture::getPicColor)
                .list();
        //如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        //将目标颜色转为Color对象
        //decode 方法
        Color targetColor = Color.decode(picColor);
        //根据欧式距离计算颜色相似度
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    //提取颜色的主色调
                    String hexColor = picture.getPicColor();
                    //如果没有主色调，则滞后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    //越大颜色越近似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                //只取前十二个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    @Override
    public boolean flushPictureColor(Long spaceId, User loginUser) {
        //1. 参数校验
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        //2.  校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无刷新权限");
        }
        //3.  查询该空间下的图片
        List<Picture> pictureList = this.lambdaQuery()
                //空间Id
                .eq(Picture::getSpaceId, spaceId)
                //为空的才需要刷新
                .isNull(Picture::getPicColor)
                .list();
        //4.通过api服务进行刷新
        //http://examples-1251000004.cos.ap-shanghai.myqcloud.com/sample.jpeg?imageAve
        List<String> toFlushPictureUrlList = pictureList.stream().map(picture -> {
            String url = picture.getUrl();
            return url + "?imageAve";
        }).collect(Collectors.toList());
        HashMap<Long, String> idsColor = flushPictureColors.getColorList(pictureList,toFlushPictureUrlList);
        idsColor.forEach((id, color) -> {
            UpdateWrapper<Picture> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id)
                    .set("picColor", color);
            boolean b = this.update(updateWrapper);
            ThrowUtils.throwIf(!b, ErrorCode.OPERATION_ERROR);
        });
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();



        // 1. 校验参数
        ThrowUtils.throwIf(spaceId == null || CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 2. 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间访问权限");
        }

        // 3. 查询指定图片，仅选择需要的字段
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();

        if (pictureList.isEmpty()) {
            return;
        }
        // 4. 更新分类和标签
        pictureList.forEach(picture -> {
            if (StrUtil.isNotBlank(category)) {
                picture.setCategory(category);
            }
            if (CollUtil.isNotEmpty(tags)) {
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        //批量重命名
        fillPictureWithNameRule(pictureList, nameRule);

        // 5. 批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }



}




